<script setup lang="tsx">
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { getConfigList, deleteConfig } from '@/api/config/admin'
import { type ConfigItem } from '@/api/config/types'
import { ContentWrap } from '@/components/ContentWrap'
import { ElMessage, ElMessageBox } from 'element-plus'
import { JsonEditor } from '@/components/JsonEditor'

const searchFormInit = {
  key: '',
  pageNum: 1,
  pageSize: 10
}

// 搜索表单数据
const searchForm = reactive({ ...searchFormInit })
const router = useRouter()

// 数据状态
const pageList = ref<ConfigItem[]>([])
const loading = ref(false)
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取配置列表
const fetchPageList = async () => {
  loading.value = true
  try {
    const params = {
      key: searchForm.key || undefined,
      pageNum: pagination.value.currentPage,
      pageSize: pagination.value.pageSize
    }

    const response = await getConfigList(params)
    if (response.code === 200) {
      pageList.value = response.data.list
      pagination.value.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取配置列表失败')
    }
  } catch (error) {
    ElMessage.error('获取配置列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchPageList()
}

// 重置搜索条件
const handleReset = () => {
  Object.assign(searchForm, searchFormInit)
  pagination.value.currentPage = 1
  fetchPageList()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
  fetchPageList()
}

const handleCurrentChange = (val: number) => {
  pagination.value.currentPage = val
  fetchPageList()
}

// 判断是否为JSON格式
const isJson = (str: string) => {
  try {
    JSON.parse(str)
    return true
  } catch (e) {
    return false
  }
}

// 跳转到新增页面
const jumpToAddPage = () => {
  router.push({ name: 'ConfigCreate' })
}

// 跳转到编辑页面
const jumpToEditPage = (row: ConfigItem) => {
  router.push({ name: 'ConfigEdit', params: { id: row.id } })
}

// 删除配置项
const deleteRecord = async (row: ConfigItem) => {
  try {
    await ElMessageBox.confirm(`确定要删除键名为"${row.key}"的配置吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await deleteConfig(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      fetchPageList()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 初始化
onMounted(() => {
  fetchPageList()
})
</script>

<template>
  <ContentWrap title="配置管理">
    <!-- 搜索表单 -->
    <div>
      <el-form :model="searchForm" label-width="100px" inline>
        <el-form-item label="键名">
          <el-input
            v-model="searchForm.key"
            placeholder="请输入键名"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="jumpToAddPage">新增配置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 列表 -->
    <el-table :data="pageList" style="width: 100%" v-loading="loading" border>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="key" label="键名" />
      <el-table-column prop="value" label="值">
        <template #default="scope">
          <div v-if="isJson(scope.row.value)" style="text-align: left">
            <JsonEditor :model-value="JSON.parse(scope.row.value)" readonly />
          </div>
          <div v-else>
            {{ scope.row.value }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column prop="updatedAt" label="更新时间" width="180" />
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <div class="button-container">
            <el-button size="small" type="primary" @click="jumpToEditPage(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteRecord(scope.row)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 20px; text-align: right"
    />
  </ContentWrap>
</template>

<style scoped>
.button-container {
  display: flex;
  flex-direction: column; /* 垂直排列，实现换行效果 */
  align-items: center; /* 右对齐 */
  gap: 8px; /* 按钮间距 */
}
.button-container :deep(.el-button) {
  margin: 0; /* 重置按钮默认外边距 */
}
</style>
